package com.automailerbot.mailreader;

import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

//使用说明
//        📥 前提条件：
//        登录你的 Gmail
//
//        访问：https://myaccount.google.com/apppasswords
//
//        生成一个 App Password（选择 “Mail” + “Other”）
//
//        用这个密码作为 appPassword
//
//        curl "http://localhost:8080/api/mail/read/gmail?email=your@gmail.com&password=app-specific-password"
@Service
public class GmailMailReader {

    public void readInbox(String email, String appPassword) throws Exception {
        Properties props = new Properties();
        props.put("mail.store.protocol", "imaps");
        props.put("mail.imap.host", "imap.gmail.com");
        props.put("mail.imap.port", "993");
        props.put("mail.imap.ssl.enable", "true");

        Session session = Session.getInstance(props);
        Store store = session.getStore("imaps");
        store.connect("imap.gmail.com", email, appPassword);

        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);

        Message[] messages = inbox.getMessages();
        int count = Math.min(messages.length, 5); // 只读取最新的5封

        for (int i = messages.length - count; i < messages.length; i++) {
            Message message = messages[i];
            System.out.println("📧 Subject: " + message.getSubject());
            System.out.println("From: " + message.getFrom()[0]);
            System.out.println("Content: " + getTextFromMessage(message));
            System.out.println("-----------------------------");
        }

        inbox.close(false);
        store.close();
    }

    private String getTextFromMessage(Message message) throws Exception {
        if (message.isMimeType("text/plain")) {
            return message.getContent().toString();
        } else if (message.isMimeType("multipart/*")) {
            MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
            return mimeMultipart.getBodyPart(0).getContent().toString();
        }
        return "";
    }
}


